package com.heima.wemedia.service.inpl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.common.constants.wemedia.NewsAutoScanConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.PageResponseResult;
import com.heima.model.admin.dtos.ResponseResult;
import com.heima.model.admin.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsDTO;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;
    /**
     * 查询所有自媒体文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findNewsList(WmNewsPageReqDTO dto) {
        //检验参数
        if(dto==null){
         return   ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"无效参数");
        }


        //条件封装执行查询
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //执行模糊查询条件
         queryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()),
                WmNews::getTitle, dto.getKeyword());
        // 判断  按照id查询
                queryWrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());
                //判断文章有无状态  按照状态信息查询
                queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
               //发布时间>=开始时间
            queryWrapper.ge(dto.getBeginPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate());
                //发布时间<=开始时间
            queryWrapper.le(dto.getEndPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate());

        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //按照登录用户ID去查询
        queryWrapper.eq(WmNews::getUserId,wmUser.getId());
        //按照创建时间降序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        //分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //执行查询
        IPage<WmNews> pageResult =page(page, queryWrapper);
        //返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
                //获取分页结果
                result.setData(pageResult.getRecords());
                //处理文章图片
                result.setHost(webSite);
                return result;
    }

    /**
     * 自媒体文章发布
     * @param dto
     * @return
     */
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //参数校验
       if(StringUtils.isBlank(dto.getContent())){
           CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
       }
        Short status = dto.getStatus();
       if(!WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(status)&& !WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(status)){
           CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章状态错误");
       }
        WmUser user = WmThreadLocalUtils.getUser();
       if(user==null){
           CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
       }
        //保存或修改文章
                WmNews wmNews=new WmNews();
                //把 WmNewsDTO的属性拷贝到 wmNews对象中
        BeanUtils.copyProperties(dto,wmNews);
        //如果文章布局是自动的,需要设置为null
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //处理dto参数  images封面集合 list===>String  转换成字符串
           String  image= imageListToStr(dto.getImages(),webSite);
        //先set赋值
        wmNews.setImages(image);
        //在保存
        saveWmNews(wmNews);
        //3.1: 保存文章内容和素材的关联关系
        // TODO 3.1 抽取内容中所有的图片url路径
       List<String> imageList= parseContentImages(wmNews.getContent());
        // TODO 3.2 保存文章内容和素材的关联关系
                //引用的素材url路径列表   文章id   引用类型
                    saveRelativeInfo(imageList,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);

        // TODO 3.3 保存文章封面中的图片和素材关系  封面可能是选择自动或者是无图
                    saveRelativeInfoForGover(dto,wmNews,imageList);
        // TODO: 发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,wmNews.getId());
      log.info("成功发送  待审核消息==>队列:{},文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,wmNews.getId());
        return  ResponseResult.okResult();
    }

    /**
     * 根据文章id查询
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1:参数检查
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //执行查询
        WmNews wmNews =new WmNews();
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return  result;
    }

    /**
     * 删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1:检查参数
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
        //2:获取数据
        WmNews wmNews =new WmNews();
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3: 判断当前文章的状态   status==9  enable==1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
        && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)
        ){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已经发布,不能删除");
        }
        //4: 去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5: 删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1: 检查参数
        if(dto==null || dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable==null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&& !WemediaConstants.WM_NEWS_DOWN.equals(enable))
        ){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        // 查询文章
        WmNews wmNews =getById(dto.getId());
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3: 判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态,不能上下架");
        }
        //4: 修改文章状态, 同步到app端(后期做) TODO:
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                    .set(WmNews::getEnable,dto.getEnable()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //查询参数
        dto.checkParam();
        //记录当前页
        Integer currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //2分页查询
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);
        //3:返回结果
        ResponseResult result=new PageResponseResult(currentPage,dto.getSize(),count,wmNewsVOList);
        result.setHost(webSite);

        return result;
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Autowired
    WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //参数检查
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2:查询文章信息
        WmNews wmNews =getById(id);
        if(wmNews==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3:查询作者
        WmUser wmUser =null;
        if(wmNews.getUserId()!=null){
            wmUser=wmUserMapper.selectById(wmNews.getUserId());
        }
        //4:封装vo信息返回
        WmNewsVO wmNewsVO =new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        if(wmUser != null){
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVO);
        responseResult.setHost(webSite);


        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1: 参数检查
        if(dto==null || dto.getId()==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2: 文章查询
        WmNews wmNews =getById(dto.getId());
        if(wmNews==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态   不能为9  已发布
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3: 修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        //TODO  通知定时发布文章

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     *生成封面内容  并 保存封面和素材的关联关系
     * @param dto
     * @param wmNews
     * @param imageList
     */
    private void saveRelativeInfoForGover(WmNewsDTO dto, WmNews wmNews, List<String> imageList) {
            //1: 入参中封面集合属性
        List<String> images = dto.getImages();
        //2: 如果type为-1  代表要根据内容图片集合  自动生成封面
            if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
                //2.1 集合数量大于2多图  wmNews设置为3(多图)  在内容图片集合中  截取前3张图片作为封面
                    if(imageList.size()> 2 ){
                        wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                     images= imageList.stream().limit(3).collect(Collectors.toList());
                    }else  if(imageList.size()>0 && imageList.size()<=2){
                        //2.2 集合数量大于0 小于等于2  wmNews设置为1(单图)  在内容图片集合中  截取前1张图片作为封面
                        wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                        images=imageList.stream().limit(1).collect(Collectors.toList());
                    }else {
                        //2.3 设置为无图
                        wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                        images=null;
                    }
                //更新
                updateById(wmNews);
            }
            // 判断最终封面集合是否为空
            if(CollectionUtils.isNotEmpty(images)){
                //去除url的路径前缀
             images=images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
                saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);  //保存封面和素材的关联关系
            }
    }



    /**
     *
     * @param imageList   select * from wm_material where url in(url , url2, url3) and user_id=?
     * @param newId
     * @param type
     */
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    private void saveRelativeInfo(List<String> imageList, Integer newsId, Short type) {
                //1: 根据素材url列表  +  登录人id    查询出对应的素材列表
        List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, imageList).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
                //判断关联的素材是否为空
                if(CollectionUtils.isEmpty(wmMaterialList)){
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的素材信息不存在");
                }

        //2:  将得到的素材列表转化成map  key:素材url  value:id
        Map<String, Integer> urlAndIdMap = wmMaterialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));


        //3: 遍历imageList 素材列表,判断每一个素材是否存在  ,   收集id到集合
        List<Integer> materialIds=new ArrayList<>();
        for (String materialUrl : imageList) {
            if(!urlAndIdMap.containsKey(materialUrl)){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的素材信息不存在");
            }
            materialIds.add(urlAndIdMap.get(materialUrl));
        }
                //4: 调用mapper的批量插入方法,保存关联关系
                   wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);
    }

    /**
     *  抽取内容中所有图片
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        //  "[{type:"image",value:"图片url"},{},{}]"
        //1: 将内容json字符串转化为 List<Map>  集合
        List<Map> mapList = JSONArray.parseArray(content, Map.class);
        //筛选
      return   mapList.stream().filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(map -> (String)map.get("value"))
                .map(url -> url.replaceAll(webSite,""))  //截取图片前缀,把前缀替换为空
                .collect(Collectors.toList());  //将数据收集到集合中

    }

    /**
     * 保存或修改文章
     * @param wmNews 文章对象(前端传递)
     */
    private void saveWmNews(WmNews wmNews) {
           wmNews.setCreatedTime(new Date());  //创建时间
            wmNews.setUserId(WmThreadLocalUtils.getUser().getId()); //获取自媒体用户ID
            wmNews.setSubmitedTime(new Date());  //创建提交时间
            wmNews.setEnable(WemediaConstants.WM_NEWS_UP);  //上架
            if(wmNews.getId()==null){ //保存操作
                save(wmNews);
            }else {   //修改
                // 当前文章 和  素材关系表数据删除
                wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
                                    updateById(wmNews);
            }
    }

    /**
     * 图片列表转字符串,并取出图片前缀
     * @param images  图片列表
     * @param webSite  图片前缀
     * @return
     */
    private String imageListToStr(List<String> images, String webSite) {
                return images.stream()  //获取流
                                .map((url)->url.replace(webSite,"")) //对流数据的中间操作
                                .collect(Collectors.joining(","));
    }


}
